<?php
require_once 'vendor/autoload.php'; // 导入必要的依赖

use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHandler
{
    private $key;
    private $algorithm;

    public function __construct($key, $algorithm = 'HS256')
    {
        $this->key = $key;
        $this->algorithm = $algorithm;
    }

    /**
     * 生成 JWT
     * @param array $payload JWT 的负载部分
     * @return string 返回生成的 JWT
     */
    public function generateToken(array $payload)
    {
        return JWT::encode($payload, $this->key, $this->algorithm);
    }

    /**
     * 验证 JWT
     * @param string $jwt 需要验证的 JWT
     * @return array|null 返回解码后的负载部分，验证失败返回 null
     */
    public function verifyToken($jwt)
    {
        try {
            $decoded = JWT::decode($jwt, new Key($this->key, $this->algorithm));
            return (array) $decoded;
        } catch (Exception $e) {
            // 验证失败，返回 null
            return null;
        }
    }
}